<?php

/**
 * alltosun.com 终端设备控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 刘德洪 (Liudh@alltosun.com) $
 * $Date: 20151124 $
 * $Id$
 */
class Action
{
    private $per_page = 30;

    /**
     * 显示列表
     */
    public function index() {

        $page_no = $status = $search_filter = $type = $is_excel = null;

        extract(URLTracker::init(array(
            'page_no' => 1,
            'status' => 2,
            'search_filter' => array(),
            'type' => 'ALL',
            'is_excel' => 0,
        )));

        // 拼装搜索条件
        $filter = array();

        if (-1 != $status) {
            $filter['status'] = $status;
        } else {
            $filter['status >= '] = '0';
        }
        if ($type != 'ALL') {
            $filter['type'] = $type;
        }
        $filter['id >'] = 0;
        // 合伙人ID的过滤 待会儿实现
        if (isset($search_filter['mobile']) && $search_filter['mobile']) {
            $filter['agency_id'] = user_helper::get_user_ids_by_mobile($search_filter['mobile']);
        }

        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'] . ' 00:00:00';
        }

        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'] . ' 23:59:59';
        }

        $relation_count = _model('store_device_relation')->getTotal($filter);
        if ($relation_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($relation_count)) {
                Response::assign('pager', $pager);
            }
            $device_by = ' ORDER BY `id` DESC ';
            if ($is_excel != 1) {
                $device_by .= $pager->getLimit($page_no);
            }
            $relation_info = _model('store_device_relation')->getList($filter, $device_by);
            $region_list = area_helper::get_code_area_list();
            foreach ($relation_info as $k => $v) {
                $relation_info[$k]['device_no'] = device_helper::get_device_code_by_id($v['dev_id']);
                if ($relation_info[$k]) {
                    $store_info = store_helper::get_store($relation_info[$k]['store_id']);
                    $relation_info[$k]['agency_id'] = $store_info['agency_id'];
                    $relation_info[$k]['realname'] = user_helper::get_realname_by_id($store_info['agency_id']);

                    if ($store_info) {
                        $store_info['province'] = @$region_list[$store_info['province_id']];
                        $store_info['city'] = @$region_list[$store_info['city_id']];
                        $store_info['county'] = @$region_list[$store_info['district_id']];
                    } else {
                        $store_info['province'] = '';
                        $store_info['city'] = '';
                        $store_info['county'] = '';
                    }
                } else {
                    $store_info = array();
                }
                $relation_info[$k]['store_info'] = $store_info;
            }
            if ($is_excel == 1) {
                $this->export_excel($relation_info);
            }

            Response::assign('count', $relation_count);
        }
        if (empty($relation_info)) {
            $relation_info = array();
        }
        Response::assign('device_list', $relation_info);
        Response::assign('status', $status);
        Response::assign('search_filter', $search_filter);
        Response::display('admin/export_device_list.html');
    }

    /**
     * 修改状态
     */
    public function change_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', -1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $info = _uri('store_machine', $id);
        if ($status == $info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        _model('store_machine')->update($id, array('status' => $status));

        return 'ok';
    }


    /**
     * 获取设备号记录列表
     */
    public function get_device_no_record() {
        $id = Request::getParam('id', 0);
        $device_no = Request::getParam('device_no', '');
        if (!$id || !$device_no) {
            return array('没有设备id或设备号', 'error', AnUrl('device/admin'));
        }

        $record_list = array();
        $record_list = _widget('store')->get_device_no_record($id, $device_no);
        if ($record_list) {
            foreach ($record_list as $k => $v) {
                $store_info = store_helper::get_store($v['store_id']);
                if ($store_info) {
                    $province_info = area_helper::get_area_info(@$store_info['province_id']);
                    $city_info = area_helper::get_area_info(@$store_info['city_id']);
                    $county_info = area_helper::get_area_info(@$store_info['district_id']);
                    $store_info['province'] = @$province_info['area'];
                    $store_info['city'] = @$city_info['area'];
                    $store_info['county'] = @$county_info['area'];
                } else {
                    $store_info['province'] = '';
                    $store_info['city'] = '';
                    $store_info['county'] = '';
                }

                $record_list[$k]['store_info'] = $store_info;
            }
        }

        Response::assign('type', $type);
        Response::assign('record_list', $record_list);
        Response::assign('device_no', $device_no);
        Response::display('admin/export_device_no_record.html');

    }

    /**
     * 设备绑定信息
     */
    public function export_excel($list = array()) {
        $device_list = array();
        foreach ($list as $k => $v) {
            $device_list[$k]['add_time'] = @$v['add_time'];
            $device_list[$k]['device_no'] = @$v['device_no'];
            $device_list[$k]['status'] = @device_config::$STATUS[$v['status']];
            $device_list[$k]['realname'] = @$v['realname'];
            $device_list[$k]['agency_id'] = @$v['agency_id'];
            $device_list[$k]['store_id'] = @$v['store_id'];
            $device_list[$k]['store_name'] = @$v['store_info']['title'] . '(' . @$v['store_info']['title_branch'] . ')';
            $device_list[$k]['province'] = @$v['store_info']['province'];
            $device_list[$k]['city'] = @$v['store_info']['city'];
            $device_list[$k]['county'] = @$v['store_info']['district'];
            $device_list[$k]['address'] = @$v['store_info']['address'];
        }
        $device_lists = array();
        foreach ($device_list as $k => $v) {
            $device_lists[] = $v;
        }
        $lines = array();
        foreach ($device_lists as $k => $v) {
            array_push($lines, array(
                $v['add_time'],
                $v['device_no'],
                $v['status'],
                $v['realname'],
                $v['agency_id'],
                $v['store_id'],
                $v['store_name'],
                $v['province'],
                $v['city'],
                $v['county'],
                $v['address'],
            ));
        }
        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        // 哪几列
        $col_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K');
        // 第一排的标题
        $col_title_arr = array('日期', '箱体编码（序列号）', '状态（已绑定）', '合伙人', '合伙人ID', '绑定商店ID', '绑定商店名称', '省', '市', '县', '地址');

        foreach ($col_arr as $k => $v) {
            //设置单位格内容A1,B1,C1,D1
            $objActSheet->setCellValue($v . "1", $col_title_arr[$k]);
        }
        //填充单元格
        $key = 2;
        foreach ($device_lists as $k => $v) {
            foreach ($col_arr as $k2 => $v2) {
                $place = $v2 . $key;
                $objActSheet->setCellValue($place, $lines[$k][$k2]);
            }
            $key++;
        }

        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        //$title = trim($catebirthday_gift_recordry_name."表").".xls";
        $title = "设备绑定信息.xls";
        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }
        header("Content-Disposition: attachment; filename=" . $title);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }

    public function save_dealer_store_data() {
        _widget('admin_data.data')->save_dealer_store_data();
    }
}
